<template>
  <Dialog
    v-model:visible="visible"
    modal
    :header="props.ng && props.ng.id ? '编辑配置' : '添加配置'"
    :style="{ width: '50rem' }"
  >
    <div class="flex items-center gap-4 mb-4">
      <label for="username" class="font-semibold w-24">Name</label>
      <InputText id="username" v-model="formData.name" class="flex-auto" autocomplete="off" />
    </div>

    <div class="flex items-center gap-4 mb-4">
      <label for="exec-path" class="font-semibold w-24">Exec</label>
      <InputText
        id="exec-path"
        disabled
        v-model="formData.execPath"
        class="flex-auto"
        autocomplete="off"
      />
      <Button icon="pi pi-cog" aria-label="Config" @click="openSelectFileDialog" />
    </div>
    <div class="flex items-center gap-4 mb-4">
      <label for="work-dir" class="font-semibold w-24">WorkDir</label>
      <InputText
        id="work-dir"
        disabled
        v-model="formData.workDir"
        class="flex-auto"
        autocomplete="off"
      />
      <Button icon="pi pi-cog" aria-label="Config" @click="openSelectDirDialog" />
    </div>
    <div class="flex justify-end gap-2">
      <Button type="button" label="Cancel" severity="secondary" @click="visible = false"></Button>
      <Button type="button" label="Save" :disabled="isOk" @click="saveEvent"></Button>
    </div>
  </Dialog>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import type { NginxInfoDto } from '@/views/tools/nginx/nginx-info.ts'
import type { NginxInfo } from '@/types/dt/Dt.ts'
const visible = defineModel<boolean>('visible', {})
const props = defineProps<{
  ng: NginxInfo | undefined
}>()
const formData = ref<NginxInfoDto>({
  name: '',
  execPath: '',
  workDir: '',
})

// 选择nginx 工作目录
const openSelectDirDialog: () => Promise<void> = async () => {
  try {
    return await window.DefaultDt.selectDir().then((value) => {
      formData.value.workDir = value || ''
    })
  } catch (err) {
    console.log(err)
  }
}
const openSelectFileDialog: () => Promise<void> = async () => {
  try {
    return await window.DefaultDt.selectFile().then((value) => {
      formData.value.execPath = value || ''
    })
  } catch (err) {
    console.log(err)
  }
}
const emit = defineEmits<{ 'save-config': [NginxInfoDto] }>()
const saveEvent = () => {
  emit('save-config', formData.value)
}

const isOk = computed(function () {
  return !formData.value.workDir || !formData.value.execPath || !formData.value.name
})

watch(visible, (value) => {
  if (!value) {
    formData.value = { name: '', execPath: '', workDir: '' }
  } else {
    if (props.ng) {
      const ng = props.ng
      formData.value.workDir = ng.workDir
      formData.value.name = ng.name
      formData.value.execPath = ng.execPath
      formData.value.id = ng.id
    }
  }
})
</script>

<style scoped lang="scss"></style>
